package com.xb.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.xb.demo.entity.Browser;
import com.xb.demo.entity.Data;
import com.xb.demo.utils.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.sound.midi.Soundbank;
import java.io.*;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @ClassName DataController
 * @Description TODO
 * @Author YLZ
 * @Date 2018/7/12 16:25
 * @Version 1.0
 **/


@RestController
@RequestMapping("/log")
public class DataController {


    //Logger logger = LoggerFactory.getLogger(DataController.class);

//    @Autowired
//    private JedisUtil jedisUtil;
   static BufferedWriter out;

    static {
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream("/home/server/data/log1.txt", true)));
//            out = new BufferedWriter(new OutputStreamWriter(
//                    new FileOutputStream("D:\\ff.txt", true)));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }



    @RequestMapping(value = {"/newData"},method = RequestMethod.GET)
    public void data(HttpServletRequest req){

        String resultJson = "";

        try {
            String lm_id = req.getParameter("lm_id") == null ? "" : req.getParameter("lm_id");
            String useragent = req.getHeader("User-Agent") == null ? "" : req.getHeader("User-Agent");
            String referer = req.getParameter("referer") == null ? "" : req.getParameter("referer");
            String screen = req.getParameter("screen") == null ? "" : req.getParameter("screen");
            String gpu = req.getParameter("gpu") == null ? "" : req.getParameter("gpu");
            String title = req.getParameter("title") == null ? "" : req.getParameter("title");

            String content =req.getParameter("content") == null ? "" : req.getParameter("content");
            if(StringUtils.isNotEmpty(content)){
                content=content.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                URLDecoder.decode(content,"utf-8");
            }
            String engine = req.getParameter("engine") ==null ? "" : req.getParameter("engine");
            String isShow = req.getParameter("isShow") == null ? "" : req.getParameter("isShow");
            String site_id = req.getParameter("site_id") == null ? "" : req.getParameter("site_id");
            String browser = BrowserUtils.getBrowser(useragent).brand;

            String ip = IPAddrUtils.getIpAddr(req);




//        String ip = "1.197.224.9";
//        String ip = "119.177.123.138";
//        String ip= "122.112.13.238";
            String country = "";
            String province = "";
            String city = "";
            String isp = "";
            String lon = "";
            String lat = "";
            if(ip.length()>0 && ip.length()<=15 && !ip.equals("unknown")) {
                JSONArray jsonIP = IPparseUtils.getArea(ip);
                if (jsonIP.size() > 1) {
                    country = jsonIP.get(1).toString();
                    province = jsonIP.get(2).toString();
                    city = jsonIP.get(3).toString();
                    isp = jsonIP.get(5).toString();
                    lon = jsonIP.get(9).toString();
                    lat = jsonIP.get(10).toString();
                }
            }else{
                country = "";
                province = "";
                city = "";
                isp = "";
                lon = "";
                lat = "";
            }
            String addtime = DateUtils.getSystemTime("yyyy-MM-dd HH:mm:ss", Long.valueOf(System.currentTimeMillis()));
            Date time = Calendar.getInstance().getTime();
            int times = Integer.parseInt(DateUtils.getString2(System.currentTimeMillis(),"HH"));
            String uuid = req.getParameter("uuid") == null ? "" : req.getParameter("uuid");
            String m_dex = lm_id+"_"+DateUtils.getString2(Long.valueOf(System.currentTimeMillis()),"yyyyMMdd");


            Data data = new Data();
            data.setLm_id(lm_id);
            data.setUseragent(useragent);
            data.setReferer(referer);


            String url = req.getParameter("url") == null ? "" : req.getParameter("url");
            if(StringUtils.isEmpty(url)){
                data.setUrl("");
                data.setHost("");
            }else{
                url=URLDecoder.decode(url,"utf-8");
                URL URL = new URL(url);
                String host = URL.getHost();
                data.setUrl(url);
                data.setHost(host);
            }
            data.setScreen(screen);
            data.setGpu(gpu);
            data.setTitle(title);
            data.setContent(content);
            data.setEngine(engine);
            data.setIsShow(isShow);
            data.setSiteid(site_id);
            data.setBrowser(browser);
            data.setIp(ip);
            data.setCountry(country);
            data.setProvince(province);
            data.setCity(city);
            data.setIsp(isp);
            data.setLon(lon);
            data.setLat(lat);
            data.setAddtime(addtime);
            data.setTime(time);
            data.setM_dex(m_dex);
            data.setTimes(times);
            data.setUuid(uuid);


            //待删除
            data.setXforwarded(IPAddrUtils.getIp1(req));
            data.setProxyClientIP(IPAddrUtils.getIp2(req));
            data.setwLProxyClientIP(IPAddrUtils.getIp3(req));
            data.setRemoteAddr(IPAddrUtils.getIp4(req));
            data.setXrealIP(IPAddrUtils.getIp5(req));
            //待删除


            resultJson = JsonUtils.obj2JsonString(data);

            //kafka方式
            // KafkaUtils.sendMessage(resultJson, "test_log");
            //redis方式
            //jedisUtil.sendMessage("list_log",resultJson);
            //写文件方式
            appendText2(resultJson);
        } catch (Exception e) {
            //logger.error("gg_"+e.getMessage());
            //e.printStackTrace();
        }
    }


    @RequestMapping(value = {"/test"},method = RequestMethod.GET)
    public @ResponseBody
    Map<String,Object> test(HttpServletRequest req){
        ModelMap modelMap=new ModelMap();
        String ip=IPAddrUtils.getIpAddr(req);
        modelMap.put("ip",ip);
        return modelMap;
    }


    private  void appendText( String conent) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream("/home/server/data/log.txt", true)));
            out.write(conent+"\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private  void appendText2( String conent) {
        try {
            out.write(conent+"\r\n");
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    public static void main(String[] args) {
//        Integer index = 1200 % 1000;//计算下标
//        System.out.println(index);

        /*String ua="Mozilla/5.0 (Linux; Android 7.1.1; OPPO A83 Build/N6F26Q; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044376 Mobile Safari/537.36 MicroMessenger/6.7.3.1360(0x26070336) NetType/WIFI Language/zh_CN Process/tools";
        Browser browser=BrowserUtils.getBrowser(ua);

        System.out.println(browser.brand);*/





    }

}
